package jianzhiOffer;

/**
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 * <p>
 * 1 2 3
 * 4 5 6
 * 7 8 9
 *
 * @author 司松坡
 * @createTime 2023年04月07日
 */
public class Jian29 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) {
            return new int[0];
        }
        int n = matrix.length;
        int m = matrix[0].length;
        boolean[][] site = new boolean[n][m];
        int[] res = new int[n * m];
        //定义方向 1：向右 2：向下 3;向左 4：向上
        int direction = 1;
        int row = 0;
        int arrange = 0;
        //初始化目前位置
        for (int i = 0; i < m * n; i++) {
            if (direction == 1) {
                res[i] = matrix[arrange][row];
                site[arrange][row] = true;
                if (row + 1 < m && !site[arrange][row+1]) {
                    row++;
                } else {
                    direction = 2;
                    arrange++;
                }
                continue;
            }
            if (direction == 2) {
                res[i] = matrix[arrange][row];
                site[arrange][row] = true;
                if (arrange + 1 < n && !site[arrange+1][row]) {
                    arrange++;
                } else {
                    direction = 3;
                    row--;
                }
                continue;
            }
            if (direction == 3) {
                res[i] = matrix[arrange][row];
                site[arrange][row] = true;
                if (row - 1 >= 0 && !site[arrange][row-1]) {
                    row--;
                } else {
                    direction = 4;
                    arrange--;
                }
                continue;
            }
            if (direction == 4) {
                res[i] = matrix[arrange][row];
                site[arrange][row] = true;
                if (arrange - 1 >= 0 && !site[arrange-1][row]) {
                    arrange--;
                } else {
                    direction = 1;
                    row++;
                }
            }
        }
        return res;

    }

}
